package com.ncloud.aaaa.service.impl;

import java.util.Date;
import java.util.List;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ncloud.aaaa.model.Role;
import com.ncloud.aaaa.repository.RoleRepository;
import com.ncloud.aaaa.service.RoleService;
import com.ncloud.common.enmus.ResultEnum;
import com.ncloud.common.exception.UserException;
import com.ncloud.param.service.SequenceService;

@Service
public class RoleServiceImpl implements RoleService {
	
	private static final Logger logger = LogManager.getLogger(RoleServiceImpl.class);
	@Autowired
	private RoleRepository repository;
	@Reference
	private SequenceService sequenceService;
	@Autowired
	private RoleBusiServiceImpl roleBusiServiceImpl;
	
	public List<Role> getRoleList(Long userId) {
		return repository.getRoleListByAccount(userId);
	}

	@Override
	public JSONObject addRole(JSONObject json) {
		if(!json.containsKey("chnlId") || !json.containsKey("roleName"))
			throw new UserException(ResultEnum.PARAM_ERROR);
		JSONObject result = new JSONObject();
		result.put("status", HttpStatus.CREATED);
		try {
			Role role = JSON.parseObject(json.toJSONString(), Role.class);
			Long roleId = sequenceService.getSequence("ROLE_ID_SEQ");
			role.setRoleId(roleId);
			Date date = new Date();
			if(role.getIsSys()==null)
				role.setIsSys("0");
			role.setCreateTime(date);
			role.setUpdateTime(date);
			Role rrole = repository.save(role);
			logger.info("创建角色role="+rrole);
			result.put("role", JSON.parseObject(JSON.toJSONString(rrole)));
		} catch (Exception e) {
			throw new UserException(ResultEnum.DATABASE_ERROR);
		}
		return result;
	}

	@Override
	public Object createUserRole(JSONObject json) {
		if(!json.containsKey("roleId") || !json.containsKey("userId")){
			throw new UserException(ResultEnum.PARAM_ERROR);
		}
		roleBusiServiceImpl.createUserRole(json);
		return HttpStatus.CREATED;
	}

	@Override
	public Object deleteUserRole(JSONObject json) {
		if(!json.containsKey("userId")){
			throw new UserException(ResultEnum.PARAM_ERROR);
		}
		roleBusiServiceImpl.deleteUserRole(json);
		return HttpStatus.OK;
	}

	@Override
	public Object updateUserRole(JSONObject json) {
		if(!json.containsKey("roleId") || !json.containsKey("userId")){
			throw new UserException(ResultEnum.PARAM_ERROR);
		}
		roleBusiServiceImpl.updateUserRole(json);
		return HttpStatus.OK;
	}


}
